@file:Suppress("DEPRECATION")

package com.cvte.sunkit.utils

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Environment
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

object ImageSaveUtil {
    fun saveBitmap2file(bmp: Bitmap, context: Context, num: String, baseFile: File) {
        val fileName = "$num.JPEG"
        val savePath: String = if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            baseFile.path
        } else {
            return
        }
        val filePic = File(savePath, fileName)
        try {
            if (!filePic.exists()) {
                filePic.parentFile?.mkdirs()
                filePic.createNewFile()
            }
            val fos = FileOutputStream(filePic)
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos)
            fos.flush()
            fos.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        // 其次把文件插入到系统图库
//        try {
//            MediaStore.Images.Media.insertImage(
//                context.contentResolver,
//                filePic.absolutePath,
//                fileName,
//                null
//            )
//        } catch (e: FileNotFoundException) {
//            e.printStackTrace()
//        }
        // 最后通知图库更新
        context.sendBroadcast(
            Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.parse("file://$savePath$fileName")
            )
        )
    }
}